package com.starsoft.quant.job;

import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.starsoft.frame.base.service.PreferenceService;
import com.starsoft.frame.util.StringUtil;
import com.starsoft.quant.bean.QuantAcount;
import com.starsoft.quant.executor.StrategyExecutor;
import com.starsoft.quant.service.QuantAcountService;
import com.starsoft.smdc.service.HolidayService;

@Component
public class ModelJobRegister {

	private final static Logger logger = LoggerFactory.getLogger(ModelJobRegister.class);
	
	private final static String JOB_GROUP_NAME = "quant_model_job";

	private final static String TRIGGER_GROUP_NAME = "quant_model_trigger";
	
	@Autowired
	QuantAcountService acountService;
	
	@Autowired
	Scheduler scheduler;
	
	@Autowired
	StrategyExecutor executor;
	
	@Autowired
	HolidayService holidayService;
	
	@Autowired
	PreferenceService ps;
	
	@PostConstruct
	public void register() throws SchedulerException {
		String env = ps.getPreference("env");
		if (!"prod".equals(env)) {
			logger.info("Not prod env, Don't regist Job");
			return;
		}
		logger.info("Start to register Model Job");
		List<QuantAcount> acountModels = acountService.geAcounts();
		for (QuantAcount acountModel : acountModels) {
			String jobName = this.getJobName(acountModel);
			try {
				if (checkRunnable(acountModel)) {
					updateQuantJob(acountModel);
					logger.info("Start model quant job:" + jobName);
				}
			} catch (Exception e) {
				logger.error("Start model quant job failed:" + jobName, e);
			}
		}
		logger.info("Finish register Model Job #{}", acountModels.size());
		scheduler.pauseJob(null);
	}
	
	private String getJobName(QuantAcount acountModel){
		return acountModel.getModelCode() + "_" + acountModel.getAcountId();
	}
	
	private boolean checkRunnable(QuantAcount acountModel){
		Date endDate = acountModel.getEndDate();
		if (endDate != null && endDate.before(new Date())) {
			return false;
		}
		if(!Boolean.TRUE.equals(acountModel.getRunNomally())){
			return false;
		}
		if(!StringUtil.isEmpty(acountModel.getRunCorn())){
			return true;
		}
		if(acountModel.getRunInterval()!=null){
			return true;
		}
		return false;
	}
	
	public void updateQuantJob(QuantAcount acountModel) throws SchedulerException{
		String jobName = this.getJobName(acountModel);
		JobKey jobKey = new JobKey(jobName, JOB_GROUP_NAME);
		TriggerKey triggerKey = new TriggerKey(jobName, TRIGGER_GROUP_NAME);
		
		boolean runnable = checkRunnable(acountModel);
		JobDetail jobDetail = scheduler.getJobDetail(jobKey);

		if(jobDetail==null && runnable==false){
			
		} else if(jobDetail!=null && runnable==false){
			scheduler.pauseTrigger(triggerKey);
			scheduler.unscheduleJob(triggerKey);
			scheduler.deleteJob(jobKey);
		} else if(jobDetail==null && runnable!=false){
			jobDetail = JobBuilder.newJob(ModelJob.class).withIdentity(jobKey)
					.usingJobData("acountId", acountModel.getAcountId()).build();
			jobDetail.getJobDataMap().put("executor", executor);
			jobDetail.getJobDataMap().put("holidayService", holidayService);
			String cron = getCronStr(acountModel);
			Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey)
					.withSchedule(CronScheduleBuilder.cronSchedule(cron)).startNow().build();
			scheduler.scheduleJob(jobDetail, trigger);
		} else {
			CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
			String cron = getCronStr(acountModel);
			trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
					.withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
			scheduler.rescheduleJob(triggerKey, trigger);
		}
	}
	
	private String getCronStr(QuantAcount acountModel) {
		String cron = null;
		if (!StringUtil.isEmpty(acountModel.getRunCorn())) {
			cron = acountModel.getRunCorn().trim();
		} else if (acountModel.getRunInterval() != null) {
			cron = String.format("0 0/%s 9-14 ? * 2-6", acountModel.getRunInterval());
		}
		return cron;
	}
	
}
